package com.wuchengdong.web.extend.exception;

import com.wuchengdong.web.extend.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

//全局异常处理
@Slf4j
@ControllerAdvice(annotations = {Controller.class, RestController.class})
@ResponseBody
public class GlobalExceptionHandler {
    //数据库中unique约束报错
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler1(SQLIntegrityConstraintViolationException e){
        //解读异常信息 向前端返回原因
        String message = e.getMessage();
        if(message.contains("Duplicate entry")){
            String[] strings = message.split(" ");
            return R.error(strings[2] + "重复");
        }else {
            return R.error("未知错误");
        }
    }
    @ExceptionHandler(FileNotFoundException.class)
    public R<String> fileNotFoundException(FileNotFoundException e) {
        return R.error("文件路径出错！！！");
    }

    @ExceptionHandler(AuthException.class)
    public R<String> authException(AuthException e) {
        return R.error("token认证错误: "+e.getMessage());
    }

    /**
     * 通用异常
     */
    @ExceptionHandler(Exception.class)
    public R<String> exceptionHandler(Exception e) {
        e.printStackTrace();
        return R.error(e.getMessage());
    }
}
